package hw.ats.apps;

import hw.ats.news.R;
import hw.ats.news.activity.DBAwareActivity;
import hw.ats.news.activity.news.RecentAct;
import hw.ats.news.activity.news.RecmdAct;
import hw.ats.news.util.App;
import hw.ats.news.util.DataLoader;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.WindowManager;
import android.widget.Toast;

import com.humanwares.util.HwUtil;
import com.tattermedia.allthataudio.audio.AudioPlayerManager;
import com.tattermedia.allthataudio.misc.DebugFlag;

public abstract class AbstractStartupAct extends DBAwareActivity {
	private final static String TAG = "AbstractStartupAct";

	@Override
	protected void onDestroy() {
		
		if (DebugFlag.isLogEnabled()) Log.d(TAG, "onDestroy()");
		closeDatabase();
		
		super.onDestroy();
	}
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)  {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }
    
    protected void init() {
        
        
        DataLoader.initDatabase(this);
        checkNetworkAvailable();
        
        //App.APP_TITLE = getString(R.string.app_nav_title_newsapp);
        App.APP_TITLE = getString(R.string.app_name_newsapp);
        
        
        // receive phone call event
        
        TelephonyManager telephonyManager  =(TelephonyManager)getSystemService(TELEPHONY_SERVICE); 
        telephonyManager.listen(new PhoneStateListener(){
			public void onCallStateChanged(int state, String incomingNumber) {
				if (state == TelephonyManager.CALL_STATE_IDLE) {
					AudioPlayerManager.getManager().resumeFromInterrupt();
				} else if (state == TelephonyManager.CALL_STATE_RINGING) {
					AudioPlayerManager.getManager().interrupt();
				} else if (state == TelephonyManager.CALL_STATE_OFFHOOK) {
				}
			}
        	
        },PhoneStateListener.LISTEN_CALL_STATE); 
        
    }
    
    protected void checkNetworkAvailable() {
    	int networkType = HwUtil.connectivityType(this);
    	if (networkType == -1) {
			new AlertDialog.Builder(this).setTitle("네트워크 접속").setMessage(
					"네트워크 접속이 실패하였습니다. 계속하시겠습니까?").setPositiveButton("계속",
					new OnClickListener() {
						public void onClick(final DialogInterface dialog,
								final int which) {
							loadRecentData();
						}
					}).setNegativeButton("종료", new OnClickListener() {
				public void onClick(final DialogInterface dialog,
						final int which) {
					finish();
				}
			}).show();
    	} else if (networkType == ConnectivityManager.TYPE_MOBILE) {
			new AlertDialog.Builder(this).setTitle("네트워크 접속").setMessage(
					"Wifi 접속이 실패하여, 3G로 네트워크 접속중 입니다.\n계속하시겠습니까?").setPositiveButton("계속",
					new OnClickListener() {
						public void onClick(final DialogInterface dialog,
								final int which) {
							loadRecentData();
						}
					}).setNegativeButton("종료", new OnClickListener() {
				public void onClick(final DialogInterface dialog,
						final int which) {
					finish();
				}
			}).show();
    	} else {
    		loadRecentData();
    	}
    }
    
    protected void gotoMain() {
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN,
        		WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
        
        // fix main
//		Intent intent = new Intent(this, RecmdAct.class);
        Intent intent = new Intent(this, RecentAct.class);
        
		startActivity(intent);
		finish();
		overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
    }
    
    protected void loadRecentData() {
    	
    	AudioPlayerManager.getManager().initialize(AbstractStartupAct.this.getPackageName());
    	
		new AsyncTask<String, Integer, Long>() {
			private String error = null;
			private ProgressDialog progressDialog;
			
			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				progressDialog = new ProgressDialog(AbstractStartupAct.this);
				progressDialog.setMessage(getString(R.string.msg_splash_init));
				progressDialog.setIndeterminate(true);
				progressDialog.setCancelable(true);
				progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
				progressDialog.show();
			}
	
			@Override
			protected Long doInBackground(String... data) {
				try {
					boolean is_update = DataLoader.loadConfig(getDBHelper());


					// 광고
					DataLoader.loadAd(getDBHelper());

					if (is_update ){
						// 카테고리 목록
						DataLoader.loadCategory(getDBHelper());
					
						// 최신글 목록 
						DataLoader.loadRecentNews(getDBHelper());  //doing in service
						

			 			// 추천글 목록
//						DataLoader.loadRecmdNews(getDBHelper()); //doing in service
					}
				} catch (Exception e) {
					Log.e(TAG, "데이터 수신 실패", e);
					error = "앱 팩토리로부터 데이터 수신이 실패하였습니다. Wifi나 3G의 접속상태를 점검하여 주십시오.";
				}
				
				// init audio player manager
		        AudioPlayerManager.getManager().loadPlayList(getReadableDatabase());

				
				//				Toast.makeText(AbstractStartupAct.this, DataLoader.getContentsUpdate(), Toast.LENGTH_SHORT).show();

				return 0L;
			}
	
			@Override
			protected void onProgressUpdate(Integer... progress) {
			}
	
			@Override
			protected void onPostExecute(Long result) {
				progressDialog.dismiss();
	
    			// 에러가 있을 경우
    			if (error != null) {
					Toast.makeText(AbstractStartupAct.this, 
							error, 
							Toast.LENGTH_SHORT).show();
    			}
    			
    			gotoMain();
			}
	
			@Override
			protected void onCancelled() {
				super.onCancelled();
				progressDialog.dismiss();
				gotoMain();
			}
		}.execute();
		
	}
}
